/***************************************************************************
 *   Copyright (C) 2007 by Alexandre Masselot,,,   *
 *   alex@alex-laptop   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "dbsequencefactoryfasta.h"

namespace bol{
DBSequenceFactoryFasta::DBSequenceFactoryFasta()
{
  setInputStream(NULL);
  m_nextline="";
  m_pattern_seqspace.assign("\\s+",boost::regex_constants::icase|boost::regex_constants::perl);
  m_pattern_header.assign(">(\\S+)\\s*(.*)");
}

void DBSequenceFactoryFasta::openFile(const string filename){
  if(inputStream()!=NULL){
    delete inputStream();
  }
  setInputStream(new ifstream(filename.c_str()));
  assert(inputStream()->good());
}
bool DBSequenceFactoryFasta::nextSequence(DBSequence& entry){
  bool first=true;
  if(inputStream()==NULL) { // the caller forgot to initialise the stream
    return false;
  }
  string seq="";
  while((m_nextline!="") || getline(*inputStream(), m_nextline)){
    //parse the header
    if(first){
      boost::cmatch matches;
      assert(boost::regex_match(m_nextline.c_str(), matches, m_pattern_header));
      entry.setAc(matches[1]);
      entry.setDescription(matches[2]);
      first=false;
      m_nextline="";
      continue;
    }
    if(m_nextline.c_str()[0]=='>')
      break;
    seq+=m_nextline;
    m_nextline="";
  }
  if (seq==""){
    return false;
  }
  seq = boost::regex_replace (seq, m_pattern_seqspace, "");
  if(entry.sequence()){
    entry.sequence()->setSequence(seq);
  }else{
    entry.setSequence(new Peptide(seq));
  }
  return true;
}

DBSequenceFactoryFasta::~DBSequenceFactoryFasta()
{
}
}
